<template>
  <div class="profile-container">
    <el-card class="profile-card">
      <template #header>
        <div class="card-header">
          <span>个人中心</span>
        </div>
      </template>

      <el-form
        :model="form"
        :rules="rules"
        ref="formRef"
        label-width="100px"
        class="profile-form"
      >
        <!-- 头像预览和输入 -->
        <el-form-item label="头像" prop="avatar">
          <div class="avatar-section">
            <div class="avatar-preview-wrapper">
              <el-avatar
                :size="100"
                :src="avatarPreview || form.avatar || defaultAvatar"
                class="avatar-preview"
              >
                <img src="https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png" />
              </el-avatar>
              <div class="avatar-upload-overlay" @click="triggerFileInput">
                <el-icon :size="24"><Camera /></el-icon>
                <span>上传图片</span>
              </div>
              <input
                ref="fileInputRef"
                type="file"
                accept="image/jpeg,image/jpg,image/png,image/gif,image/webp"
                @change="handleFileSelect"
                style="display: none"
              />
            </div>
            <div class="avatar-input">
              <el-upload
                class="avatar-uploader"
                :show-file-list="false"
                :before-upload="beforeUpload"
                :http-request="handleUpload"
                accept="image/jpeg,image/jpg,image/png,image/gif,image/webp"
              >
                <el-button type="primary" :loading="uploading">
                  <el-icon><Upload /></el-icon>
                  {{ uploading ? '上传中...' : '选择图片上传' }}
                </el-button>
              </el-upload>
              <div class="avatar-divider">
                <el-divider>或</el-divider>
              </div>
              <el-input
                v-model="form.avatar"
                placeholder="请输入头像图片URL"
                clearable
                @input="handleAvatarUrlInput"
              >
                <template #append>
                  <el-button @click="handleUseUrl">使用URL</el-button>
                </template>
              </el-input>
              <div class="avatar-tips">
                <el-text type="info" size="small">
                  支持上传图片文件（JPEG、PNG、GIF、WebP，最大5MB）或输入图片URL地址
                </el-text>
              </div>
            </div>
          </div>
        </el-form-item>

        <!-- 用户名 -->
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="form.username"
            placeholder="请输入新的用户名"
            clearable
            maxlength="20"
            show-word-limit
          />
        </el-form-item>
        <!-- 修改密码 -->
        <el-form-item label="旧密码" prop="oldPassword">
          <el-input
            v-model="form.oldPassword"
            type="password"
            placeholder="如需修改密码，请输入旧密码"
            show-password
            autocomplete="current-password"
            clearable
          />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="form.newPassword"
            type="password"
            placeholder="新密码（不少于6位）"
            show-password
            autocomplete="new-password"
            clearable
          />
        </el-form-item>
        <el-form-item label="确认新密码" prop="confirmPassword">
          <el-input
            v-model="form.confirmPassword"
            type="password"
            placeholder="再次输入新密码"
            show-password
            autocomplete="new-password"
            clearable
          />
        </el-form-item>

        <!-- 昵称 -->
        <el-form-item label="昵称" prop="nickname">
          <el-input
            v-model="form.nickname"
            placeholder="请输入昵称"
            clearable
            maxlength="20"
            show-word-limit
          />
        </el-form-item>

        <!-- 邮箱 -->
        <el-form-item label="邮箱" prop="email">
          <el-input
            v-model="form.email"
            type="email"
            placeholder="请输入邮箱地址"
            clearable
          />
        </el-form-item>

        <!-- 角色（只读） -->
        <el-form-item label="角色">
          <el-input
            v-model="roleText"
            disabled
            placeholder="角色不可修改"
          />
        </el-form-item>

        <!-- 最后更新时间 -->
        <el-form-item label="更新时间" v-if="form.updatedAt">
          <el-input
            :value="formatDate(form.updatedAt)"
            disabled
          />
        </el-form-item>

        <!-- 操作按钮 -->
        <el-form-item>
          <el-button
            type="primary"
            @click="handleSubmit"
            :loading="loading"
          >
            保存修改
          </el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useAuthStore } from '@/stores/auth'
import { getUserProfile, uploadAvatar } from '@/api/auth'
import { ElMessage } from 'element-plus'
import { Camera, Upload } from '@element-plus/icons-vue'

const authStore = useAuthStore()
const formRef = ref(null)
const fileInputRef = ref(null)
const loading = ref(false)
const uploading = ref(false)
const avatarPreview = ref('')
const defaultAvatar = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'

const form = reactive({
  id: null,
  username: '',
  nickname: '',
  email: '',
  avatar: '',
  role: '',
  updatedAt: '',
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const originalForm = reactive({
  id: null,
  username: '',
  nickname: '',
  email: '',
  avatar: '',
  role: '',
  updatedAt: '',
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 2, max: 20, message: '昵称长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  avatar: [
    {
      validator: (rule, value, callback) => {
        if (value && value.trim()) {
          // 简单的URL验证
          try {
            new URL(value)
            callback()
          } catch {
            callback(new Error('请输入有效的URL地址'))
          }
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  oldPassword: [
    {
      validator: (rule, value, callback) => {
        // 如用户填写了任一密码字段，则旧密码必填
        if (form.newPassword || form.confirmPassword) {
          if (!value) return callback(new Error('请填写旧密码'))
        }
        callback()
      },
      trigger: 'blur'
    }
  ],
  newPassword: [
    {
      validator: (rule, value, callback) => {
        if (form.oldPassword || form.confirmPassword) {
          if (!value) return callback(new Error('请填写新密码'))
          if (String(value).length < 6) return callback(new Error('新密码不少于6位'))
        }
        callback()
      },
      trigger: 'blur'
    }
  ],
  confirmPassword: [
    {
      validator: (rule, value, callback) => {
        if (form.oldPassword || form.newPassword) {
          if (!value) return callback(new Error('请确认新密码'))
          if (value !== form.newPassword) return callback(new Error('两次输入的密码不一致'))
        }
        callback()
      },
      trigger: 'blur'
    }
  ]
}

// 角色文本
const roleText = computed(() => {
  return form.role === 'admin' ? '管理员' : '普通用户'
})

// 加载用户信息
const loadUserProfile = async () => {
  loading.value = true
  try {
    const result = await getUserProfile()
    if (result.success) {
      Object.assign(form, {
        id: result.data.id,
        username: result.data.username,
        nickname: result.data.nickname || result.data.username,
        email: result.data.email,
        avatar: result.data.avatar || '',
        role: result.data.role,
        updatedAt: result.data.updatedAt
      })
      // 保存原始数据
      Object.assign(originalForm, { ...form })
    } else {
      ElMessage.error(result.error || '加载用户信息失败')
    }
  } catch (error) {
    console.error('加载用户信息错误:', error)
    ElMessage.error('加载用户信息失败')
  } finally {
    loading.value = false
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    loading.value = true

    const updateData = {
      username: form.username,
      nickname: form.nickname,
      email: form.email,
      avatar: form.avatar || ''
    }
    // 如用户填写了密码相关字段，则附加
    if (form.oldPassword || form.newPassword || form.confirmPassword) {
      updateData.oldPassword = form.oldPassword
      updateData.newPassword = form.newPassword
    }

    const result = await authStore.updateUserProfile(updateData)
    if (result.success) {
      ElMessage.success(result.message || '更新成功')
      
      // 更新表单数据
      if (result.data) {
        form.updatedAt = result.data.updatedAt || form.updatedAt
        form.username = result.data.username || form.username
        form.nickname = result.data.nickname || form.nickname
        form.email = result.data.email || form.email
        form.avatar = result.data.avatar || form.avatar
      }
      // 清空密码字段
      form.oldPassword = ''
      form.newPassword = ''
      form.confirmPassword = ''
      
      // 更新原始数据
      Object.assign(originalForm, { ...form })
    } else {
      ElMessage.error(result.error || '更新失败')
    }
  } catch (error) {
    if (error !== false) {
      // 表单验证失败时error为false，不需要显示错误
      console.error('提交表单错误:', error)
    }
  } finally {
    loading.value = false
  }
}

// 重置表单
const handleReset = () => {
  Object.assign(form, { ...originalForm })
  form.oldPassword = ''
  form.newPassword = ''
  form.confirmPassword = ''
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 触发文件选择
const triggerFileInput = () => {
  fileInputRef.value?.click()
}

// 处理文件选择
const handleFileSelect = (event) => {
  const file = event.target.files?.[0]
  if (file) {
    handleFileUpload(file)
  }
}

// 文件上传前的验证
const beforeUpload = (file) => {
  const isValidType = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp'].includes(file.type)
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isValidType) {
    ElMessage.error('只能上传图片文件（JPEG、PNG、GIF、WebP）!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB!')
    return false
  }
  
  // 预览图片
  const reader = new FileReader()
  reader.onload = (e) => {
    avatarPreview.value = e.target.result
  }
  reader.readAsDataURL(file)
  
  return false // 阻止自动上传，使用自定义上传
}

// 处理文件上传
const handleUpload = async (options) => {
  const file = options.file
  await handleFileUpload(file)
}

// 执行文件上传
const handleFileUpload = async (file) => {
  uploading.value = true
  try {
    const result = await uploadAvatar(file)
    if (result.success) {
      ElMessage.success(result.message || '头像上传成功')
      
      // 更新头像URL
      form.avatar = result.data.avatarUrl
      avatarPreview.value = ''
      
      // 使用store的方法更新用户信息（确保响应式更新）
      authStore.updateUser({
        avatar: result.data.avatarUrl
      })
      
      // 更新原始数据
      originalForm.avatar = result.data.avatarUrl
      form.updatedAt = new Date().toISOString()
      
      // 同时更新表单的updatedAt，以便显示更新时间
      if (authStore.user) {
        form.updatedAt = authStore.user.updatedAt || form.updatedAt
      }
    } else {
      ElMessage.error(result.error || '上传失败')
      avatarPreview.value = ''
    }
  } catch (error) {
    console.error('上传头像错误:', error)
    ElMessage.error('上传头像失败')
    avatarPreview.value = ''
  } finally {
    uploading.value = false
    // 清空文件输入
    if (fileInputRef.value) {
      fileInputRef.value.value = ''
    }
  }
}

// 处理头像URL输入
const handleAvatarUrlInput = () => {
  // 当用户输入URL时，清除预览
  avatarPreview.value = ''
}

// 使用URL设置头像
const handleUseUrl = () => {
  if (!form.avatar || !form.avatar.trim()) {
    ElMessage.warning('请输入头像URL')
    return
  }
  
  // 验证URL格式
  try {
    new URL(form.avatar)
    ElMessage.success('头像URL已设置')
    avatarPreview.value = ''
  } catch {
    ElMessage.error('请输入有效的URL地址')
  }
}

// 组件挂载时加载用户信息
onMounted(() => {
  loadUserProfile()
})
</script>

<style scoped>
.profile-container {
  padding: 20px;
}

.profile-card {
  max-width: 800px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: bold;
}

.profile-form {
  margin-top: 20px;
}

.avatar-section {
  display: flex;
  align-items: flex-start;
  gap: 20px;
}

.avatar-preview-wrapper {
  position: relative;
  flex-shrink: 0;
}

.avatar-preview {
  border: 2px solid #dcdfe6;
  border-radius: 50%;
  cursor: pointer;
  transition: all 0.3s;
}

.avatar-upload-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100px;
  height: 100px;
  border-radius: 50%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: white;
  cursor: pointer;
  opacity: 0;
  transition: opacity 0.3s;
  font-size: 12px;
  gap: 4px;
}

.avatar-preview-wrapper:hover .avatar-upload-overlay {
  opacity: 1;
}

.avatar-input {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.avatar-uploader {
  width: 100%;
}

.avatar-divider {
  margin: 8px 0;
}

.avatar-tips {
  margin-top: 4px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-input.is-disabled .el-input__inner) {
  background-color: #f5f7fa;
  color: #606266;
}
</style>

